// components/search/index.js
import {
  KeywordModel
} from '../../models/keyword.js'
import {
  BookModel
} from '../../models/book.js'
import {
  paginationBev
} from '../behaviors/pagination.js'

const keywordModel = new KeywordModel()
const bookModel = new BookModel()

Component({
  /**
   * 组件的属性列表
   */
  behaviors: [paginationBev],
  properties: {
    more: {
      type: String,
      observer: 'loadMore'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    searching: false,
    q: '',
    loading: false,
    loadingCenter: false
  },

  lifetimes: {
    attached: async function() {
      const data = await keywordModel.getHot()
      this.setData({
        historyWords: keywordModel.getHistory(),
        hotWords: data.hot
      })
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    loadMore: function() {
      if (!this.data.q) return
      if (this.isLocked()) return
      if (this.hasMore()) {
        this.locked()
        bookModel.search(this.getCurrentStart(), this.data.q).then(res => {
          this.setMoreData(res.books)
          this.unLocked()
        },() => this.unLocked())
      }
    },

    onCancel: function(evt) {
      this.initialize()
      this.triggerEvent('cancel', {}, {})
    },

    onDelete: function(evt) {
      this.initialize()
      this._closeResult()
    },

    onConfirm: function(evt) {
      this._showResult()
      this._showLoadingCenter()
      const q = evt.detail.value || evt.detail.text
      this.setData({q})
      bookModel.search(0,q).then(res => {
        this.setMoreData(res.books)
        this.setTotal(res.total)
        keywordModel.add2History(q)
        this._hideLoadingCenter()
      })
    },

    _showLoadingCenter: function() {
      this.setData({loadingCenter: true})
    },

    _hideLoadingCenter: function() {
      this.setData({loadingCenter: false})
    },

    _showResult: function() {
      this.setData({ searching: true})
    },

    _closeResult: function() {
      this.setData({ searching: false, q: ''})
    }
  }
})